import useRoleList from '@/components/RoleList';
import SingleUpload from '@/components/SingleUpload';
import type { UserRecord } from '@/DatabaseType/User';
import { updateUserInfo } from '@/services/user';
import type { FunFirstParam } from '@/types';
import { ResponseCode } from '@/utils/request';
import { Button, Card, Form, Input, message, Space, Switch } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';
import { useModel } from '@umijs/max';
import {
  ProDescriptions,
  ProDescriptionsItemProps,
} from '@ant-design/pro-components';

type SubmitParams = FunFirstParam<typeof updateUserInfo>;

interface InformationBaseProps {
  cardStyle?: React.CSSProperties;
}

const InformationBase: React.FC<InformationBaseProps> = ({ cardStyle }) => {
  const { initialState, refresh: fetchUserInfo } = useModel('@@initialState');
  const currentUser = initialState?.currentUser as UserRecord;
  const roleListEle = useRoleList();
  const [disabled, setDisabled] = useState(true);
  // 信息未获取到之前都是loading态
  const loading = !currentUser;

  const [formInstance] = Form.useForm();
  // 初始化值
  useEffect(() => {
    formInstance.setFieldsValue(currentUser);
  }, [currentUser, formInstance]);

  async function handleSubmit() {
    let values: SubmitParams;
    try {
      values = await formInstance.validateFields();
    } catch (error: any) {
      return;
    }

    try {
      const result = await updateUserInfo(values);
      message[result.code === ResponseCode.Fail ? 'error' : 'success']({
        content: result.message || '更新成功',
      });
      setDisabled(true);
      fetchUserInfo();
    } catch (error) {
      console.log(
        'UserInfoManagement => InformationBase => updateUserInfo',
        '请求失败',
        error,
      );
    }
  }

  const descriptionColumns: ProDescriptionsItemProps<UserRecord>[] = useMemo(
    () => [
      {
        title: '开启编辑',
        dataIndex: 'canEdit',
        render() {
          return (
            <Switch
              checkedChildren="编辑"
              unCheckedChildren="取消"
              checked={!disabled}
              onChange={(checked) => {
                setDisabled(!checked);
                if (!checked) {
                  formInstance.setFieldsValue(currentUser);
                }
              }}
            />
          );
        },
        span: 2,
      },
      {
        title: '用户名',
        dataIndex: 'username',
      },
      {
        title: '身份角色',
        dataIndex: 'roleList',
        render() {
          return roleListEle;
        },
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        valueType: 'dateTime',
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        valueType: 'dateTime',
      },
      {
        title: '昵称',
        dataIndex: 'nickname',
        render() {
          return (
            <Form.Item noStyle name="nickname">
              <Input style={{ width: '50%' }} disabled={disabled} />
            </Form.Item>
          );
        },
      },
      {
        title: '邮箱',
        dataIndex: 'email',
        render() {
          return (
            <Form.Item noStyle name="email">
              <Input style={{ width: '50%' }} disabled={disabled} />
            </Form.Item>
          );
        },
      },
      {
        title: '用户头像',
        dataIndex: 'avatarImage',
        render() {
          return (
            <Form.Item name="avatarImage" noStyle>
              <SingleUpload disabled={disabled} />
            </Form.Item>
          );
        },
      },
    ],
    [currentUser, disabled, formInstance, roleListEle],
  );

  return (
    <Card title="基础信息" style={cardStyle} loading={loading}>
      <Form form={formInstance}>
        <ProDescriptions
          column={{ xs: 1, sm: 2, md: 2 }}
          labelStyle={{ minWidth: 75 }}
          columns={descriptionColumns}
          request={async () => {
            return {
              data: currentUser,
            };
          }}
        />
        <Space>
          <Button
            type="primary"
            onClick={handleSubmit}
            key="update"
            disabled={disabled}
          >
            更新
          </Button>
        </Space>
      </Form>
    </Card>
  );
};

export default InformationBase;
